import React, { useState, useCallback } from 'react';
import { connect } from 'umi';
import { history } from 'umi';
import { Table, Card, Tag, Button, Row, Col, Tooltip, Spin } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import Pagination from '@/components/Pagination';
import { getQualityTag, getHour, getStringBr, formatTaskOverdue, formatDate } from '../utils';
import { useEmployeeListAllQuery, useDepartmentEvalUserCount } from '../hooks';
import Search from './Search';
import CompanyTree from '../components/CompanyTree';
import styles from './index.less';

// 筛选数组
const filtersWorkloadFlag = [
    {
        text: '正常',
        value: '1'
    },
    {
        text: '不足',
        value: '2'
    },
    {
        text: '超额',
        value: '3'
    }
];
const filtersEvalFlag = [
    {
        text: '否',
        value: '0'
    },
    {
        text: '是',
        value: '1'
    }
];
const filtersMap = {
    workloadFlag: filtersWorkloadFlag,
    lastWorkloadFlag: filtersWorkloadFlag,
    evalFlag: filtersEvalFlag
};

/* 2020-4-3
注释的代码是产品要求隐藏的产品线和项目组筛选条件
http://jira.vv.cn:8000/browse/VVDEV-3327
*/
const Employee = ({ location, route: { code }, user }) => {
    const { query } = location;
    // 维护参数
    const [params, setParams] = useState({
        pageNo: query.pageNo || 1,
        pageSize: query.pageSize || 10,
        employeeName: query.employeeName || '',
        cdType: query.cdType || '1',
        companyId: query.companyId || user.currentUser.companyId,
        departmentId: query.departmentId || null,
        reportType: query.reportType ? Number(query.reportType) : 1,
        // productId: query.productId,
        // projectGroupId: query.projectGroupId,
        workloadFlag: query.workloadFlag ? String(query.workloadFlag) : null,
        lastWorkloadFlag: query.lastWorkloadFlag ? String(query.lastWorkloadFlag) : null,
        evalFlag: query.evalFlag ? String(query.evalFlag) : null,
        startDate: query.startDate || formatDate('1', moment()).startDate,
        endDate: query.endDate || formatDate('1', moment()).endDate
    });
    const [employeeListLoading, dataSource, total] = useEmployeeListAllQuery(params);
    const [treeLoading, departmentEvalUserCount] = useDepartmentEvalUserCount();

    // 筛选默认值
    const getFilterValue = field => {
        const list = filtersMap[field];
        const value = params[field];
        const exist = list.find(item => item.value === value);
        if (exist) {
            return [exist.value];
        }
        return [];
    };

    const columns = [
        {
            title: '员工姓名',
            dataIndex: 'employeeName',
            key: 'employeeName',
            width: 100,
            fixed: 'left',
            render: (text, record) => (
                <Button
                    type="link"
                    style={{ padding: 0 }}
                    onClick={() => {
                        history.push(
                            `/stat/workStat/workOverview/work/employeeinfo?reportType=${params.reportType}&userId=${record.evalUserId}&startDate=${params.startDate}&endDate=${params.endDate}`
                        );
                    }}
                >
                    {text}
                </Button>
            )
        },
        {
            title: '是否考核',
            dataIndex: 'evalFlag',
            key: 'evalFlag',
            align: 'center',
            fixed: 'left',
            width: 110,
            filters: filtersEvalFlag,
            filterMultiple: false,
            filteredValue: getFilterValue('evalFlag'),
            render: (data, record) => (
                <>
                    {data === 0 && (
                        <Tooltip placement="topLeft" title={record.noevalReason}>
                            <span style={{ color: '#FFA22D' }}>否</span>
                        </Tooltip>
                    )}
                    {data === 1 && <span>是</span>}
                </>
            )
        },
        // {
        //     title: '产品线',
        //     dataIndex: 'productName',
        //     key: 'productName'
        // },
        // {
        //     title: '项目组',
        //     dataIndex: 'projectGroupName',
        //     key: 'projectGroupName',
        //     width: 180,
        //     render: data => getStringBr(data)
        // },
        {
            title: '职位',
            dataIndex: 'postName',
            key: 'postName',
            render: data => getStringBr(data)
        },

        {
            title: `上${Number(params.reportType) === 1 ? '周' : '月'}实际工作`,
            children: [
                {
                    title: '工作量',
                    dataIndex: 'lastActualTotalWorkloadNum',
                    key: 'lastActualTotalWorkloadNum',
                    align: 'center',
                    render: data => (
                        <>
                            <span style={{ marginRight: 10 }}>{getHour(data)}小时</span>
                        </>
                    )
                },
                {
                    title: '饱和度',
                    dataIndex: 'lastActualTotalWorkloadSaturability',
                    key: 'lastActualTotalWorkloadSaturability',
                    align: 'center',
                    filters: filtersWorkloadFlag,
                    filterMultiple: false,
                    filteredValue: getFilterValue('lastWorkloadFlag'),
                    render: (text, record) => (
                        <>
                            <span style={{ marginRight: 10 }}>{text || text === 0 ? `${text}%` : '--'}</span>
                            {record.lastWorkloadFlag === 2 && <span className={styles.InsTag}>不足</span>}
                            {record.lastWorkloadFlag === 3 && <span className={styles.exceTag}>超额</span>}
                        </>
                    )
                }
            ]
        },
        {
            title: `本${Number(params.reportType) === 1 ? '周' : '月'}计划工作`,
            children: [
                {
                    title: '工作量',
                    dataIndex: 'planTotalWorkloadNum',
                    key: 'planTotalWorkloadNum',
                    align: 'center',
                    render: data => (
                        <>
                            <span style={{ marginRight: 10 }}>{getHour(data)}小时</span>
                        </>
                    )
                },
                {
                    title: '饱和度',
                    dataIndex: 'planTotalWorkloadSaturability',
                    key: 'planTotalWorkloadSaturability',
                    align: 'center',
                    filters: filtersWorkloadFlag,
                    filterMultiple: false,
                    filteredValue: getFilterValue('workloadFlag'),
                    render: (text, record) => (
                        <>
                            <span style={{ marginRight: 10 }}>{text || text === 0 ? `${text}%` : '--'}</span>
                            {record.workloadFlag === 2 && <span className={styles.InsTag}>不足</span>}
                            {record.workloadFlag === 3 && <span className={styles.exceTag}>超额</span>}
                        </>
                    )
                }
            ]
        },
        {
            title: '任务数',
            dataIndex: 'totalTaskNum',
            key: 'totalTaskNum',
            align: 'center',
            render: (data, record) =>
                formatTaskOverdue(data, record.overdueDoneTaskNum, record.overdueNonexecutionTaskNum)
        },
        {
            title: '任务质量',
            dataIndex: 'evalScore',
            key: 'evalScore',
            align: 'center',
            render: (data, record) => {
                const rt = getQualityTag(record.evalRank);
                return (
                    <>
                        <span style={{ marginRight: 5 }}>{data && data.toFixed(2)}</span>
                        <Tag color={rt.color}>{rt.label}</Tag>
                    </>
                );
            }
        },
        // {
        //     title: '标准工作量',
        //     dataIndex: 'standardTotalWorkloadNum',
        //     key: 'standardTotalWorkloadNum',
        //     render: data => `${getHour(data)}小时`
        // },
        {
            title: '日均Bug（个）',
            dataIndex: 'avageDayBugNum',
            key: 'avageDayBugNum',
            align: 'center',
            render: data => (data === 0 ? '--' : data.toFixed(2))
        }
    ];

    // 搜索查询
    const handleSearch = obj => {
        setParams({ ...params, ...obj, pageNo: 1 });
    };

    // 公司部门选择回调
    const handleSelectCompany = obj => {
        const { companyId, departmentId, cdType } = obj;
        setParams({ ...params, companyId, departmentId, cdType, pageNo: 1 });
    };

    // 筛选
    const onChangeTable = (pagination, filters) => {
        const extraQuery = {};

        if (filters && Object.keys(filters).length) {
            Object.keys(filters).forEach(item => {
                const [filterValue] = filters[item];
                if (item === 'planTotalWorkloadSaturability') {
                    extraQuery.workloadFlag = filterValue;
                } else if (item === 'lastActualTotalWorkloadSaturability') {
                    extraQuery.lastWorkloadFlag = filterValue;
                } else {
                    extraQuery[item] = filterValue;
                }
            });
        }
        setParams({ ...params, ...extraQuery, pageNo: 1 });
    };

    /* 翻页 */
    const handlePageNoChange = useCallback(
        ({ pageSize, current }) => {
            setParams({
                ...params,
                pageNo: current || Number(params.pageNo),
                pageSize: pageSize || Number(params.pageSize)
            });
        },
        [params]
    );

    return (
        <PageHeaderWrapper>
            <Card>
                <Row gutter={24}>
                    <Col xs={{ span: 5 }} lg={{ span: 6 }}>
                        {/* 节点的key值由 cdType-companyId-id 拼接而成，节点的 value 值为id，公司节点的 companyId 与id相同 */}
                        <Spin spinning={treeLoading}>
                            <CompanyTree
                                routeCode={code}
                                defaultKeys={`${!params.departmentId ? '0' : params.cdType}-${
                                    params.companyId
                                }-${params.departmentId || '0'}`}
                                partakeData={departmentEvalUserCount}
                                onSelect={handleSelectCompany}
                            />
                        </Spin>
                    </Col>
                    <Col xs={{ span: 19 }} lg={{ span: 18 }}>
                        <div style={{ marginBottom: 24 }}>
                            <Search query={params} onSearch={handleSearch} />
                        </div>
                        <Table
                            bordered
                            rowKey="id"
                            columns={columns}
                            dataSource={dataSource}
                            onChange={onChangeTable}
                            pagination={false}
                            loading={employeeListLoading}
                            scroll={{ x: 'max-content' }}
                        />
                        <Pagination
                            total={Number(total)}
                            pageSize={Number(params.pageSize)}
                            current={Number(params.pageNo)}
                            onChange={handlePageNoChange}
                        />
                    </Col>
                </Row>
            </Card>
        </PageHeaderWrapper>
    );
};

const mapStateToProps = ({ user }) => ({ user });

export default connect(mapStateToProps)(Employee);
